package category

import (
	"context"
	"github.com/gin-gonic/gin"
	"nnxy-search-api/search-order-api/api"
	"nnxy-search-api/search-order-api/global"
	"nnxy-search-api/search-order-api/global/response"
	"nnxy-search-api/search-order-api/proto"
	"nnxy-search-api/search-order-api/validator/forms"
	"strconv"
)

func New(ctx *gin.Context) {
	categoryForm := forms.CategoryForm{}
	err := ctx.ShouldBindJSON(&categoryForm)
	if err != nil {
		api.HandleValidatorError(err, ctx)
		return
	}
	_, err = global.OrderSrvClient.CreateCategory(context.Background(), &proto.CategoryRequest{
		Title: categoryForm.Title,
		Pid:   categoryForm.Pid,
		Level: categoryForm.Level,
	})
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.Success(ctx)
}
func List(ctx *gin.Context) {
	pageStr := ctx.DefaultQuery("page", "1")
	limitStr := ctx.DefaultQuery("limit", "10")
	page, _ := strconv.Atoi(pageStr)
	limit, _ := strconv.Atoi(limitStr)
	req := proto.CategoryRequest{
		Page:  int32(page),
		Limit: int32(limit),
	}
	if title := ctx.Query("title"); title != "" {
		req.Title = title
	}
	rsp, err := global.OrderSrvClient.GetCategoryList(context.Background(), &req)
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	result := map[string]interface{}{
		"total": rsp.Total,
	}

	data := make([]map[string]interface{}, 0)
	for _, category := range rsp.Data {
		data = append(data, conventCategoryToRsp(category))
	}
	result["data"] = data
	response.SuccessData(ctx, result)
}

func Detail(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	req := proto.CategoryRequest{
		Id: int64(id),
	}
	rsp, err := global.OrderSrvClient.GetCategoryById(context.Background(), &req)
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.SuccessData(ctx, conventCategoryToRsp(rsp))
}

func Update(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	categoryForm := forms.CategoryForm{}
	err := ctx.ShouldBindJSON(&categoryForm)
	if err != nil {
		api.HandleValidatorError(err, ctx)
		return
	}
	_, err = global.OrderSrvClient.UpdateCategory(context.Background(), &proto.CategoryRequest{
		Id:    int64(id),
		Title: categoryForm.Title,
		Pid:   categoryForm.Pid,
		Level: categoryForm.Level,
	})
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.Success(ctx)
}

func Delete(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	req := proto.CategoryRequest{
		Id: int64(id),
	}
	_, err := global.OrderSrvClient.DeleteCategory(context.Background(), &req)
	if err != nil {
		api.HandlerGrpcErrorToHttp(err, ctx)
		return
	}
	response.SuccessMsg(ctx, "删除成功")
}

func conventCategoryToRsp(category *proto.CategoryInfoRsp) map[string]interface{} {
	item := map[string]interface{}{
		"id":    category.Id,
		"pid":   category.Pid,
		"title": category.Title,
		"level": category.Level,
	}
	return item
}
